package com.ycz.algorithm.utils.queue;

import com.ycz.algorithm.utils.linkedlist.ListNode;

/**
 * @author yancz
 * @ClassName LinkedListQueue
 * @description: 基于链表实现的队列
 * @date 2024-11-26 16:12:47
 * @version: 1.0
 */
public class LinkedListQueue {

    private ListNode front; // 队首元素

    private ListNode rear; // 队尾元素

    private int queueSize; // 队列长度

    // 队列初始化
    public LinkedListQueue() {
        front = null;
        rear = null;
    }

    // 获取队列长度
    public int size() {
        return queueSize;
    }

    // 判断队空
    public boolean isEmpty() {
        return queueSize == 0;
    }

    // 元素入队
    public void push(int num) {
        ListNode node = new ListNode(num);
        if (front == null) { // 如果队头为空，则令队头队尾元素均等于入队元素
            front = node;
        } else { // 如果队非空，则令队尾元素等于入队元素
            rear.next = node;
        }
        rear = node;
        queueSize++;
    }

    // 元素出队
    public int pop() {
        int num = peek();
        front = front.next;
        queueSize--;
        return num;
    }

    // 访问队首元素
    public int peek() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("队空！");
        }
        return front.val;
    }

    // 转为数组
    public int[] toArray() {
        ListNode node = front;
        int[] res = new int[size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = node.val;
            node = node.next;
        }
        return res;
    }

    public static void main(String[] args) {
        LinkedListQueue linkedListQueue = new LinkedListQueue();
        // 入队
        linkedListQueue.push(1);
        linkedListQueue.push(2);
        linkedListQueue.push(3);
        linkedListQueue.push(4);
        linkedListQueue.push(5);
        commonPrint(linkedListQueue);
        System.out.println("队列长度：" + linkedListQueue.size());
        System.out.println("队首元素：" + linkedListQueue.peek());
        // 出队
        int num = linkedListQueue.pop();
        System.out.println("出队元素：" + num);
        commonPrint(linkedListQueue);
        System.out.println("队列长度：" + linkedListQueue.size());
        System.out.println("队首元素：" + linkedListQueue.peek());
        System.out.println("队空？" + linkedListQueue.isEmpty());
    }

    public static void commonPrint(LinkedListQueue linkedListQueue) {
        int[] arrs = linkedListQueue.toArray();
        for (int i : arrs) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }

}
